package com.ykl.tm.interceptor;

import com.ykl.tm.util.HttpUtil;
import com.ykl.tm.util.SSOClientUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Component
public class SSOClientInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //1.判断是否存在会话
    HttpSession session = request.getSession();
    if (session.getAttribute("isLogin") != null && (Boolean) session.getAttribute("isLogin")) {
      return true;
    }
    //2.判断是否存在token
    if (request.getParameter("token")!=null) {
      String token = request.getParameter("token");
      //防止伪造，拿到服务器去验证
      //服务器地址
      String httpUrl = SSOClientUtil.SERVER_URL_PREFIX + "/verify";
      //需要验证的参数
      Map<String, String> params = new HashMap<String, String>();
      params.put("token", token);
      params.put("clientUrl", SSOClientUtil.getClientLogOutUrl());
      params.put("jsessionId", session.getId());
      try {
        String isVerify = HttpUtil.setHttpRequest(httpUrl, params);
        if (isVerify.equals("true")) {
          session.setAttribute("isLogin", true);
          return true;
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    SSOClientUtil.redirectToSSOURl(request, response);
    return false;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

  }
}
